package com.ruoyi.HKISAPI.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/ISAPI/")
@RestController
public class ISAPIDemo {



    // 分页查询(未过滤)
    @GetMapping("/ContentMgmt/InputProxy/channels/demo")
    public Map<String,Object> selectPageAlarmEvent() {

        return  getChannels();
    }

    public Map<String,Object> getChannels() {
        Map<String,Object> data = new HashMap<>();

        String url = "";
        String url2 = "";
        List<Map> JsonMapList = new ArrayList<>();
        List<Map> JsonMapList2 = new ArrayList<>();


            Map<String,Object> result = new HashMap<>();

            String vcrIp = "192.168.7.50";
            String vcrPort = "80";
            String vcrUsername = "admin";
            String vcrPassword = "sxygsj123";
            String vcrName = "录像机50";

            String responseData =null;
            String responseData2 =null;

            url = "http://"+vcrIp+":"+vcrPort+"/ISAPI/ContentMgmt/InputProxy/channels";
            url2 = "http://"+vcrIp+":"+vcrPort+"/ISAPI/ContentMgmt/InputProxy/channels/status";

            try{
                responseData= performGetRequest(url, vcrUsername, vcrPassword);
                responseData2= performGetRequest(url2, vcrUsername, vcrPassword);

                Map<String, Object> resultMap = convertXmlToJsonMap(responseData);
                Map<String, Object> resultMap2 = convertXmlToJsonMap(responseData2);

                List<Map<String,Object>> InputProxyChannel = (List<Map<String,Object>>)resultMap.get("InputProxyChannel");
                List<Map<String,Object>> InputProxyChannelStatus = (List<Map<String,Object>>)resultMap2.get("InputProxyChannelStatus");
                if (InputProxyChannel!=null&&InputProxyChannel.size()>0){


                    for (int i = 0; i < InputProxyChannel.size(); i++) {
                        // 获取当前通道的源输入端口描述符
                        Map<String, Object> sourceInputPortDescriptor = (Map<String, Object>) InputProxyChannel.get(i).get("sourceInputPortDescriptor");
                        // 获取对应的状态信息
                        String online = (String) InputProxyChannelStatus.get(i).get("online"); // 确保这里也使用i来获取对应状态
                        // 创建一个新的映射来保存更新后的值，包括原有的键值对和新的"online"状态
                        String id = (String)InputProxyChannel.get(i).get("id");
                        String name = (String)InputProxyChannel.get(i).get("name");
                        Map<String, Object> updatedMap = new HashMap<>(InputProxyChannel.get(i));
                        String ipAddress = (String)sourceInputPortDescriptor.get("ipAddress");
                        String proxyProtocol = (String)sourceInputPortDescriptor.get("proxyProtocol");
                        String managePortNo = (String)sourceInputPortDescriptor.get("managePortNo");
                        String srcInputPort = (String)sourceInputPortDescriptor.get("srcInputPort");
                        String userName = (String)sourceInputPortDescriptor.get("userName");
                        String streamType = (String)sourceInputPortDescriptor.get("streamType");
                        String deviceID = (String)sourceInputPortDescriptor.get("deviceID");

                        updatedMap.put("id", id);
                        updatedMap.put("online", online);
                        updatedMap.put("ipAddress", ipAddress);
                        updatedMap.put("proxyProtocol", proxyProtocol);
                        updatedMap.put("managePortNo", managePortNo);
                        updatedMap.put("srcInputPort", srcInputPort);
                        updatedMap.put("userName", userName);
                        updatedMap.put("streamType", streamType);
                        updatedMap.put("deviceID", deviceID);
                        // 使用更新后的映射替换原列表中的映射
                        InputProxyChannel.set(i, updatedMap);

                        String isOnline;
                        if ("true".equals(online)){
                            isOnline="1";
                        }else {
                            isOnline="2";
                        }

                    }

                }


//            List<MonitorPoint> list = toMonitorList(monitorListJsonStr);
                JsonMapList.add(resultMap);
                JsonMapList2.add(resultMap2);
//
//                System.out.println("Result Map2: " + resultMap2);
                result.put("responseData",responseData);
                result.put("responseData2",responseData2);

                data.put("InputProxyChannel",InputProxyChannel);


            }catch (IOException e) {
                e.printStackTrace();
            }

        //

        data.put("JsonMapList",JsonMapList);
        data.put("JsonMapList2",JsonMapList2);

        return data;
    }

    public static String performGetRequest(String url, String username, String password) throws IOException {
        // 创建凭据提供程序并设置用户名和密码
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build()) {

            // 创建 GET 请求
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Accept", "application/json"); // 设置请求头

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 处理响应
                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                System.out.println(entity);
                if (entity != null) {
                    return EntityUtils.toString(entity, "UTF-8");
                }
            }
        }
        return null;
    }

    public static Map<String, Object> convertXmlToJsonMap(String xml) {
        try {
            //创建 XmlMapper 对象
            XmlMapper xmlMapper = new XmlMapper();
            System.out.println("进行convertXmlToJsonMap方法");
            // 读取 XML 并将其转换为 JsonNode
            // 假设 xml 是一个 String 类型的 XML 数据
            byte[] bytes = xml.getBytes(StandardCharsets.UTF_8); // 显式指定 UTF-8 编码
//            byte[] bytes = xml.getBytes();
//            System.out.println(bytes);
            JsonNode node = xmlMapper.readTree(bytes);

            // 创建 ObjectMapper 对象
            ObjectMapper jsonMapper = new ObjectMapper();
            // 将 JsonNode 转换为 JSON 字符串
            String jsonString = jsonMapper.writeValueAsString(node);
//            System.out.println(jsonString);
            // 将 JSON 字符串转换为 Map
            return jsonMapper.readValue(jsonString, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
